package com.eventosgasteiz.server;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;

import com.eventosgasteiz.server.bbdd.Event;
import com.eventosgasteiz.server.bbdd.Imagen;
import com.eventosgasteiz.server.bbdd.PMF;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class CrearEventoNuevo extends HttpServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1477736008820465940L;
	private static final Logger log = Logger.getLogger(CrearEventoNuevo.class.getName());
	
	private static final String FIELD_NAME = "name";
	private static final String FIELD_DESC = "desc";
	private static final String FIELD_LUGAR = "lugar";
	private static final String FIELD_FECHA_INICIO = "fecha_inicio";
	private static final String FIELD_FECHA_FIN = "fecha_fin";
	private static final String FIELD_HORARIO = "horario";
	private static final String FIELD_PRECIO = "precio";
	private static final String FIELD_ORGANIZADOR = "organizador";
	private static final String FIELD_TELEFONO = "telefono";
	private static final String FIELD_URL = "url";
	//private static final String FIELD_PHOTOPATH = "photopath";
	//private static final String FIELD_THUMBPHOTOPATH = "thumbphotopath";
	private static final String FIELD_LOCATION = "location";
	private static final String FIELD_LATITUDE = "latitude";
	private static final String FIELD_LONGITUDE = "longitude";

	private static final int PHOTO_SIZE = 250;
	private static final int THUMBNAIL_SIZE = 100;
	
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
    	
    	String name = null;
    	String desc = null;
    	String lugar = null;
    	String fecha_inicio = null;
    	String fecha_fin = null;
    	String horario = null;
    	Double precio = null;
    	String organizador = null;
    	String telefono = null;
    	String url = null;
    	String photopath = null;
    	String thumbphotopath = null;
    	String location = null;
    	Double latitude = null;
    	Double longitude = null;
    	
    	req.setCharacterEncoding("ISO-8859-1");
    	
    	try {
	    	boolean isMultipart = ServletFileUpload.isMultipartContent(req);
	    	log.info("Es multipart: "+isMultipart);
	    	
	    	if (isMultipart) {
		    	// Create a new file upload handler
		    	ServletFileUpload upload = new ServletFileUpload();
		    	
		    	// Parse the request
		    	FileItemIterator iter;
				iter = upload.getItemIterator(req);
	
		    	while (iter.hasNext()) {
		    	    FileItemStream item = iter.next();
		    	    String fieldId = item.getFieldName();
		    	    InputStream stream = item.openStream();
		    	    if (item.isFormField()) {
		    	    	String itemValue = Streams.asString(stream, "ISO-8859-1");
		    	        log.info("Form field " + fieldId + " with value "
		    	            + itemValue + " detected.");
		    	        if (FIELD_NAME.equals(fieldId)) {
		    	        	name = itemValue;
		    	        	System.out.println("");
		    	        } else if (FIELD_DESC.equals(fieldId)) {
		    	        	desc = itemValue;
		    	        } else if (FIELD_LUGAR.equals(fieldId)) {
		    	        	lugar = itemValue;
		    	        } else if (FIELD_FECHA_INICIO.equals(fieldId)) {
		    	        	fecha_inicio = itemValue;
		    	        } else if (FIELD_FECHA_FIN.equals(fieldId)) {
		    	        	fecha_fin = itemValue;
		    	        } else if (FIELD_HORARIO.equals(fieldId)) {
		    	        	horario = itemValue;
		    	        } else if (FIELD_PRECIO.equals(fieldId)) {
		    	        	if (!"".equals(itemValue)) {
		    	        		precio = new Double(itemValue);
		    	        	}
		    	        } else if (FIELD_ORGANIZADOR.equals(fieldId)) {
		    	        	organizador = itemValue;
		    	        } else if (FIELD_TELEFONO.equals(fieldId)) {
		    	        	telefono = itemValue;
		    	        } else if (FIELD_URL.equals(fieldId)) {
		    	        	url = itemValue;
		    	        } else if (FIELD_LOCATION.equals(fieldId)) {
		    	        	location = itemValue;
		    	        } else if (FIELD_LATITUDE.equals(fieldId)) {
		    	        	if (!"".equals(itemValue)) {
		    	        		latitude = new Double(itemValue);
		    	        	}
		    	        } else if (FIELD_LONGITUDE.equals(fieldId)) {
		    	        	if (!"".equals(itemValue)) {
		    	        		longitude = new Double(itemValue);
		    	        	}
		    	        }
		    	    } else {
		    	        System.out.println("File field " + fieldId + " with file name "
		    	            + item.getName() + " detected.");
		    	        // Process the input stream
		    	        byte[] bytes = IOUtils.toByteArray(stream);
		    	        if (bytes.length==0){continue; }
		    	        
		    	        ImagesService imagesService = ImagesServiceFactory.getImagesService();
		    	        Image formImage = ImagesServiceFactory.makeImage(bytes);
		    	        Image formImageThumb = ImagesServiceFactory.makeImage(bytes);
		    	        int imageWidth = formImage.getWidth();
		    	        int imageHeight = formImage.getHeight();
		    	        int imageWidthThumb;
		    	        int imageHeightThumb;
		    	        if (imageWidth>PHOTO_SIZE || imageHeight>PHOTO_SIZE){
		    	        	if (imageWidth >= imageHeight) {
		    	        		imageHeight = imageHeight*PHOTO_SIZE/imageWidth;
		    	        		imageWidth = PHOTO_SIZE;
		    	        	} else {
		    	        		imageWidth = imageWidth*PHOTO_SIZE/imageHeight;
		    	        		imageHeight = PHOTO_SIZE;
		    	        	}
		    	        }
		    	        Transform resize = ImagesServiceFactory.makeResize(imageWidth, imageHeight);
		    	        Image formImageNew = imagesService.applyTransform(resize, formImage);
		    	        if (imageWidth >= imageHeight) {
	    	        		imageHeightThumb = imageHeight*THUMBNAIL_SIZE/imageWidth;
	    	        		imageWidthThumb = THUMBNAIL_SIZE;
	    	        	} else {
	    	        		imageWidthThumb = imageWidth*THUMBNAIL_SIZE/imageHeight;
	    	        		imageHeightThumb = THUMBNAIL_SIZE;
	    	        	}
		    	        Transform resizeThumb = ImagesServiceFactory.makeResize(imageWidthThumb, imageHeightThumb);
		    	        Image thumbImage = imagesService.applyTransform(resizeThumb, formImageThumb);
		    	        
		    	        // construct our entity objects
		    	        Blob imageBlob = new Blob(formImageNew.getImageData());
		    	        Imagen myImage = new Imagen(item.getName(), imageBlob);
		    	        // construct our entity objects
		    	        Blob imageThumbBlob = new Blob(thumbImage.getImageData());
		    	        Imagen myImageThumb = new Imagen("thumb_"+item.getName(), imageThumbBlob);

		    	        String host = System.getProperties().getProperty("host");
		    	        log.info(host);
		    	        
		    	        // persist image
		    	        PersistenceManager pm = PMF.get().getPersistenceManager();
		    	        myImage = pm.makePersistent(myImage);
		    	        photopath = host+"getImage?id="+myImage.getId().getId()+myImage.getName().substring(myImage.getName().indexOf("."));
		    	        pm.close();
		    	        PersistenceManager pm2 = PMF.get().getPersistenceManager();
		    	        myImageThumb = pm2.makePersistent(myImageThumb);
		    	        thumbphotopath = host+"getImage?id="+myImageThumb.getId().getId()+myImage.getName().substring(myImage.getName().indexOf("."));
		    	        pm2.close();
		    	    }
		    	}
	    	} else {
		    	name = req.getParameter("name");
		    	desc = req.getParameter("desc");
		    	lugar = req.getParameter("lugar");
		    	fecha_inicio = req.getParameter("fecha_inicio");
		    	fecha_fin = req.getParameter("fecha_fin");
		    	horario = req.getParameter("horario");
		    	if (req.getParameter("precio")!=null && !"".equals(req.getParameter("precio"))) {
		    		precio = new Double(req.getParameter("precio")).doubleValue();
		    	} else {
		    		precio = 0.0;
		    	}
		    	organizador = req.getParameter("organizador");
		    	telefono = req.getParameter("telefono");
		    	url = req.getParameter("url");
		    	photopath = req.getParameter("photopath");
		    	thumbphotopath = req.getParameter("thumbphotopath");
		    	location = req.getParameter("location");
		      	if (req.getParameter("latitude")!=null && !"".equals(req.getParameter("latitude"))) {
		      		latitude = new Double(req.getParameter("latitude")).doubleValue();
		    	}
		      	if (req.getParameter("longitude")!=null && !"".equals(req.getParameter("longitude"))) {
		      		longitude = new Double(req.getParameter("longitude")).doubleValue();
		    	}
	    	}
	    	
	        
	    	Event evento = new Event(name,
	    			desc,
	    			lugar,
	    			fecha_inicio,
	    			fecha_fin,
	    			horario,
	    			precio,
	    			organizador,
	    			telefono,
	    			url,
	    			photopath,
	    			thumbphotopath,
	    			location,
	    			latitude,
	    			longitude);
	
	        PersistenceManager pm = PMF.get().getPersistenceManager();
	        try {
	            pm.makePersistent(evento);
	        } finally {
	            pm.close();
	        }
	        log.info("Evento creado");
	        Gson json = new GsonBuilder().disableHtmlEscaping().create();
	        log.info("JSON: "+json.toJson(evento));
	        resp.sendRedirect("/ListarEventosJson.jsp");
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
